using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using WolfCarol.AvgToolkit.Command;
using WolfCarol.AvgToolkit.Save;

namespace WolfCarol.AvgToolkit.Examples
{
    [Serializable]
    public class ChoiceData
    {
        public bool IsUsed;

        public string Dialogue;

        public string Flag;

        public ChoiceData()
        {
            IsUsed = false;
            Dialogue = string.Empty;
            Flag = string.Empty;
        }
    }

    [RequireComponent(typeof(Button))]
    public class ChoiceButton : MonoBehaviour, ISavable<ChoiceData>
    {
        private ChoicePresenter m_presenter;

        private TMP_Text m_dialogueText;

        private string m_flag;

        private void Awake()
        {
            GetComponent<Button>().onClick.AddListener(OnButtonDown);
            m_dialogueText = GetComponentInChildren<TMP_Text>();
        }

        public void SetChoicePresenter(ChoicePresenter presenter) => m_presenter = presenter;

        public void SetChoice(string dialogue, string flag)
        {
            m_dialogueText.text = dialogue;
            m_flag = flag;
        }

        private void OnButtonDown()
        {
            if (m_presenter == null)
            {
                throw new NullReferenceException("ChoicePresenter did not set.");
            }

            m_presenter.OnChoiceButtonDown(m_flag);
        }

        public void Clear()
        {
            gameObject.SetActive(false);
            m_flag = string.Empty;
            m_dialogueText.text = string.Empty;
        }

        public ChoiceData Save()
        {
            return new ChoiceData()
            {
                IsUsed = gameObject.activeSelf,
                Dialogue = m_dialogueText.text,
                Flag = m_flag
            };
        }

        public void Load(ChoiceData obj)
        {
            gameObject.SetActive(obj.IsUsed);
            m_dialogueText.text = obj.Dialogue;
            m_flag = obj.Flag;
        }
    }
}
